var mysql = require('mysql');
var ou = require('../objectUtil');
var pool = mysql.createPool({
    	host : 'localhost',
    	port : 3306,
        user : 'root',
    	password : '',
    	database : 'book'
});
//打印出Pool类的所有成员
ou.allMembers(pool);
//添加监听
pool.on('connection', function(connection){
	console.log('\t获取连接');	
});
//获取一个连接并执行查询
pool.getConnection(function (err, connection){
	if(err){
		console.log(err.message);
		connection.release();
		return;	
	}
	connection.query('select * from author_ limit 0,2',function(err, rows, fields){
		if(rows.length > 0){
			for(var i = 0; i < rows.length ; i ++){
				console.log('name:' + rows[i].name);
				console.log('info:' + rows[i].info);
				console.log('----------------------');	
			}
		}
		connection.release();
	});
});
//直接执行一个查询，回调函数之后自动释放connection
pool.query('select * from author_ limit 2,3', function(err, rows, fields){
	//ou.allMembers(err);
	if(err){
		console.log(err.message);
		return;
	}
	if(rows.length > 0){
		console.log('name:' + rows[0]['name']);
		console.log('info:' + rows[0]['info']);
		console.log('----------------------');	
	}	
});
//使用pool.escape()或者connection.escape()来防止SQL注入
var sql_ = 'select * from author_ where name like ' + pool.escape('%飞%') + ' limit 1';
console.log(sql_);
pool.query(sql_, function(err, rows, fields){
	if(err){
		console.log(err.message);
		return;	
	}
	if(rows.length > 0){
		console.log('name:' + rows[0]['name']);
		console.log('info:' + rows[0]['info']);
		console.log('----------------------');		
	}	
});
//使用占位符(本质也是使用用pool.escape()或者connection.escape())
pool.query('select * from author_ where id = ?', [5], function(err, rows, fields){
	if(err){
		console.log(err.messgae);
		return;	
	}
	if(rows.length > 0){
		console.log('name:' + rows[0]['name']);
		console.log('info:' + rows[0]['info']);
		console.log('----------------------');		
	}
	pool.end();//关闭连接池，不能再获取连接了
});